package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.BJMitangMag;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //获取手机号
        String phone = user.getPhone();
        //获取验证码
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        //将验证码放入到session域中key为手机号 方便进行对比
        //session.setAttribute(phone, code);
        //优化将验证码存入redis中减少资源占用
        //手机号作为key验证码作为value保存到redis中2分钟
        redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
        //短信验证码的发送
        //BJMitangMag.codeMsg(phone, code);
        log.info(code);
        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        //获取手机号及验证码
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        //在session域中根据手机号取出验证码
        //String sessionCode = (String) session.getAttribute(phone);
        //从redis中根据手机号获取到验证码
        String redisCode = (String) redisTemplate.opsForValue().get(phone);
        //如果根据手机号在session域中取出的验证码为空 或者 取出的验证码和输入的验证码不一样 直接终止登录
        if (redisCode == null || !redisCode.equals(code)) {
            return R.error("验证码输入有误");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //对比库中的用户手机号
        wrapper.eq(User::getPhone, phone);
        //查看用户是否为null
        //null就是新用户 写入数据库
        User user = userService.getOne(wrapper);
        //这是就代表是新用户
        if (user == null) {
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            //新用户入库
            userService.save(user);
        }
        //将用户id存入session域中
        session.setAttribute("user", user.getId());
        //用户登录成功后可直接删除redis中的暂存验证码根据手机号删除即可
        redisTemplate.delete(phone);
        return R.success(user);
    }
}
